﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevTeam;
using System;
using System.Data;
using System.IO;
using System.ServiceModel;
using System.Xml.Serialization;

namespace ConfExpert.Forms.Ithalat
{
    public partial class Barsan : XForm
    {
        public Barsan()
        {
            InitializeComponent();
        }

        private void Barsan_Load(object sender, EventArgs e)
        {
            BarsanWS.EntegrasyonClient ec = new BarsanWS.EntegrasyonClient();
            string userName = AppSession.BarsanUsername;
            string password = AppSession.BarsanPassword;

            BasicHttpBinding binding = (BasicHttpBinding)ec.Endpoint.Binding;
            binding.MaxBufferSize = Int32.MaxValue;
            binding.MaxReceivedMessageSize = Int32.MaxValue;

            DateTime t = new DateTime(2016, 1, 1);
            BarsanWS.Beyanname[] b = ec.BeyannameListesi(userName, password, t);

            DataTable dB = new DataTable("Beyanname");
            dB.Columns.Add("ANTREPO", typeof(string));
            dB.Columns.Add("AY", typeof(int));
            dB.Columns.Add("UNSPED_DOSYA_NO", typeof(string));
            dB.Columns.Add("BRUTKG", typeof(float));
            dB.Columns.Add("CIKIS_ULKESI", typeof(string));
            dB.Columns.Add("Document_ROW_Id", typeof(int));
            dB.Columns.Add("DOSYA_ACILIS_TARIHI", typeof(DateTime));
            dB.Columns.Add("FARK_GUN", typeof(int));
            dB.Columns.Add("GUMRUK", typeof(string));
            dB.Columns.Add("ISLEM_BITIS_TARIHI", typeof(DateTime));
            dB.Columns.Add("KAP", typeof(float));
            dB.Columns.Add("MAL_TESLIM_TARIHI", typeof(DateTime));
            dB.Columns.Add("NAKLIYECI", typeof(string));
            dB.Columns.Add("ODEME_SEKLI", typeof(string));
            dB.Columns.Add("OZET_BEYAN_NO", typeof(string));
            dB.Columns.Add("OZET_BEYAN_TARIHI", typeof(DateTime));
            dB.Columns.Add("REFERANS", typeof(string));
            dB.Columns.Add("REJIM_KODU", typeof(string));
            dB.Columns.Add("TARIH_SAAT", typeof(DateTime));
            dB.Columns.Add("TASIT_KIMLIGI", typeof(string));
            dB.Columns.Add("YURTDISI", typeof(string));
            dB.Columns.Add("TESCIL_NO", typeof(string));
            dB.Columns.Add("TESCIL_TARIH", typeof(DateTime));
            dB.Columns.Add("TESLIM_SEKLİ", typeof(string));
            dB.Columns.Add("TICARET_ULKESI", typeof(string));
            dB.Columns.Add("TUR", typeof(string));

            DataTable dD = new DataTable("Dekont");
            dD.Columns.Add("ID", typeof(int));
            dD.Columns.Add("DekontId", typeof(int));
            dD.Columns.Add("Aciklama", typeof(string));
            dD.Columns.Add("EvrakNo", typeof(string));
            dD.Columns.Add("EvrakTarihi", typeof(DateTime));
            dD.Columns.Add("Kod", typeof(string));
            dD.Columns.Add("Tutar", typeof(float));
            dD.Columns.Add("DEKONTLAR_Id", typeof(int));
            //            dD.Columns.Add("Document_ROW_Id", typeof(int));

            DataTable dF = new DataTable("FaturaBilgi");
            dF.Columns.Add("FaturaId", typeof(int));
            dF.Columns.Add("FaturaNo", typeof(string));
            dF.Columns.Add("Tarih", typeof(DateTime));
            dF.Columns.Add("Miktar", typeof(float));
            dF.Columns.Add("Tutar", typeof(float));
            dF.Columns.Add("FATURABILGILERI_Id", typeof(int));
            //            dF.Columns.Add("Document_ROW_Id", typeof(int));

            foreach (BarsanWS.Beyanname bx in b)
            {
                DataRow rB = dB.NewRow();
                if (bx.Antrepo != null)
                    rB["ANTREPO"] = bx.Antrepo;
                rB["AY"] = bx.Ay;
                rB["UNSPED_DOSYA_NO"] = bx.BarsanDosyaNo;
                rB["BRUTKG"] = bx.BrutKg;
                rB["CIKIS_ULKESI"] = bx.CikisUlkesi;
                rB["Document_ROW_Id"] = bx.Id;
                rB["DOSYA_ACILIS_TARIHI"] = bx.DosyaAcilisTarihi;
                rB["FARK_GUN"] = bx.FarkGun;
                rB["GUMRUK"] = bx.Gumruk;
                rB["ISLEM_BITIS_TARIHI"] = bx.IslemBitisTarihi;
                rB["KAP"] = bx.Kap;
                if (bx.MalTeslimTarihi != null)
                    rB["MAL_TESLIM_TARIHI"] = bx.MalTeslimTarihi;
                rB["NAKLIYECI"] = bx.Nakliyeci;
                rB["ODEME_SEKLI"] = bx.OdemeSekli;
                rB["OZET_BEYAN_NO"] = bx.OzetBeyanNo;
                if (bx.OzetBeyanTarihi != null)
                    rB["OZET_BEYAN_TARIHI"] = bx.OzetBeyanTarihi;
                rB["REFERANS"] = bx.Referans;
                rB["REJIM_KODU"] = bx.RejimKodu;
                rB["TARIH_SAAT"] = bx.TarihSaat;
                rB["TASIT_KIMLIGI"] = bx.TasitKimligi;
                rB["YURTDISI"] = bx.TedarikciUretici;
                rB["TESCIL_NO"] = bx.TescilNo;
                rB["TESCIL_TARIH"] = bx.TescilTarihi;
                rB["TESLIM_SEKLİ"] = bx.TeslimSekli;
                rB["TICARET_ULKESI"] = bx.TicaretUlkesi;
                rB["TUR"] = bx.Tur;

                rB["Document_ROW_Id"] = bx.Id + 1e7;
                dB.Rows.Add(rB);

                foreach (BarsanWS.Dekont dx in bx.Dekontlar)
                {
                    DataRow rD = dD.NewRow();
                    rD["DEKONTLAR_Id"] = rB["Document_ROW_Id"];
                    rD["DekontId"] = dx.DekontId + 1e7;
                    rD["Aciklama"] = dx.Aciklama;
                    rD["EvrakNo"] = dx.EvrakNo;
                    if (dx.EvrakTarihi != null)
                        rD["EvrakTarihi"] = dx.EvrakTarihi;
                    rD["Kod"] = dx.Kod;
                    rD["Tutar"] = dx.Tutar;
                    dD.Rows.Add(rD);
                }

                foreach (BarsanWS.Fatura fx in bx.Faturalar)
                {
                    DataRow rF = dF.NewRow();
                    rF["FATURABILGILERI_Id"] = rB["Document_ROW_Id"];
                    rF["FaturaId"] = fx.FaturaId + 1e7;
                    rF["FaturaNo"] = fx.FaturaNo;
                    if (fx.FaturaTarihi != null)
                        rF["Tarih"] = fx.FaturaTarihi;
                    rF["Miktar"] = fx.Miktar;
                    rF["Tutar"] = fx.Tutar;
                    dF.Rows.Add(rF);
                }
            }

            /*
            DataSet d = ToDataSet((Object[])b);

            string script = string.Empty;
            foreach (DataTable dt in d.Tables)
                script += Extension.BuildCreateTableScript(dt);
            */

            int Eksik = ExecuteScalar("MergeBARSAN", dB.Serialize(), dD.Serialize(), dF.Serialize()).ToInt();
            Notify(dB.Rows.Count + " DOSYANIN BİLGİSİ GÜNCELLENDİ.");


            gridView1.Init("GetBARSAN_Tablolar");
            gridView1.AddDetailGrid(gridView2, "Document_ROW_Id", 1);
            gridView1.AddDetailGrid(gridView3, "Document_ROW_Id", 2);

            gridView1.AddColumn("DEK", typeof(int), "COUNT(Child({FK}).Document_ROW_Id)", 0);   //TODO: bunlar yukardakinin aksine niye 1 geriden geliyor, araştırılacak!
            gridView1.AddColumn("FTB", typeof(int), "COUNT(Child({FK}).Document_ROW_Id)", 1);

            gridView1.MakeColumnInvisible("Document_ROW_Id", "TIP", "FIRMA");
            gridView2.MakeColumnInvisible("DEKONTLAR_Id", "Document_ROW_Id");
            gridView3.MakeColumnInvisible("FATURABILGILERI_Id", "Document_ROW_Id");

            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;


            gridView2.FormatAsNumber(2, "Tutar");
            gridView2.AddSummary("Tutar");

            gridView3.FormatAsNumber(2, "Tutar");
            gridView3.AddSummary("Tutar");

            gridView1.FormatAsDateTime("DOSYA_ACILIS_TARIHI", "TARIH_SAAT");
            gridView1.FormatAsDate("FATURA_TARIHI", "MAL_TESLIM_TARIHI", "OZET_BEYAN_TARIHI", "TESCIL_TARIH", "ISLEM_BITIS_TARIHI");
            gridView1.FormatAsNumber(2, "FATURA_TUTARI", "MIKTAR", "BRUTKG", "ISTATISTIKI");
            gridView1.FormatAsNumber(0, "DEK", "FTB", "KAP", "FARK_GUN");
            gridView1.AddSummary("DEK", "FTB", "KAP", "FATURA_TUTARI", "BRUTKG", "ISTATISTIKI");
            gridView1.YanYanaGetirSoluna("TUR", "DEK", "FTB");
            gridView1.YanYanaGetir("REFERANS:UNSPED_DOSYA_NO");
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;

            gridView1.MakeRowSelectable();
            gridView1_FocusedRowChanged(null, null);
            gridView1.BestFitColumns();

            if (Eksik > 0)
                XtraMessageBox.Show(Eksik.ToStr() + " adet masraf kaleminin hesap kodu belli değil. Masrafların doğru hesaplanabilmesi için lütfen bunları eşleme formunda doldurun.");

            gridView1.ShowOnlyNonblankColumns();
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            gridView3.BestFitColumns();
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            tpDEK.Text = "DEKONT." + gridView2.RowCount.ToStr();
            tpFAT.Text = "FATURABILGI." + gridView3.RowCount.ToStr();

            tpDEK.PageVisible = gridView2.RowCount > 0;
            tpFAT.PageVisible = gridView3.RowCount > 0;

            if (e != null)
                if (e.FocusedRowHandle > -1)
                    txtInfo.Caption = gridView1.GetFocusedDataRow()["FATURA_NO"].ToStr();

            gridView2.BestFitColumns();
            gridView3.BestFitColumns();
        }

        public DataSet ToDataSet(object[] _objectArray)
        {
            DataSet ds = new DataSet();

            XmlSerializer xmlSerializer = new XmlSerializer(_objectArray.GetType());
            StringWriter writer = new StringWriter();
            xmlSerializer.Serialize(writer, _objectArray);
            StringReader reader = new StringReader(writer.ToStr());

            ds.ReadXml(reader);
            return ds;
        }


    }
}
